﻿using GalaSoft.MvvmLight;
using Power.View;
using GalaSoft.MvvmLight.Command;
using System.Windows;
using Power.View.Dialog;
using System.Windows.Media;
using System;
using CefSharp;
using System.Collections.Generic;
using Power.Models;
using System.IO;
using Power.Common;
using Newtonsoft.Json;

namespace Power.ViewModel
{
    public class MapViewModel : ViewModelBase
    {
        public List<MapEntity> DataList{ get; set; }
        public Map model;
        public MapViewModel(Map model)
        {
            int port = 11111;
            Common.Common.InitWebServer(port);

            this.model = model;
            this.model.MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight-2;
            this.model.SizeChanged += Model_SizeChanged;
            this.model.map.Address = $"http://127.0.0.1:{port}/map4.html";
            this.model.map.FrameLoadEnd += Map_FrameLoadEnd;
            this.model.map.JavascriptObjectRepository.Register("csharp", new JavascriptCallCSharp(this), true, BindingOptions.DefaultBinder);
        }

        private void Map_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            InitData(true);
        }

        public void InitData(bool isFirst = false) {
            //登录页面加载地图页面时，不获取后台数据
            if (!isFirst) {
                this.Data = new MainViewData() { UserName = "王小明", UserImage = "http://120.77.177.121/user.png" };
                this.DataList = new List<MapEntity>()
                {
                    new MapEntity(){ Id = 1,Longitude = 110,Latitude = 32,Name="成都管网检测项目",SectionCount = 32,SectionLength=1,DefectCount=1,RepairSuggest="测试测试测试测试测试测试",IsOpenWindow=true},
                    new MapEntity(){ Id = 2,Longitude = 120,Latitude = 30,Name="武汉管网检测项目",SectionCount = 30,SectionLength=11,DefectCount=2,RepairSuggest="测试"},
                    new MapEntity(){ Id = 3,Longitude = 115,Latitude = 33,Name="重庆管网检测项目",SectionCount = 33,SectionLength=23,DefectCount=3,RepairSuggest="测试"}
                };
            }
            //刷新前台显示数据
            if (this.model.map.CanExecuteJavascriptInMainFrame)
            {
                this.model.map.ExecuteScriptAsync($"setUserInfo('{this.Data?.UserName}','{this.Data?.UserImage}')");
                this.model.map.ExecuteScriptAsync($"setDataList('{JsonConvert.SerializeObject(this.DataList)}')");
            }
        }

        private void Model_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            //MaxImage = "";
            //窗口大小变动后调整前台最大化显示图片
            if (this.model.map.CanExecuteJavascriptInMainFrame) { 
                this.model.map.ExecuteScriptAsync($"setMinOrMaxSrc('{IsMaxImage}')");
            }
        }

        //public string MaxImage
        //{
        //    get
        //    {
        //        if (model.WindowState == WindowState.Maximized)
        //        {
        //            return "/Resources/images/max_max.png";
        //        }
        //        else
        //        {
        //            return "/Resources/images/max_normal.png";
        //        }
        //    }
        //    set
        //    {
        //        RaisePropertyChanged("MaxImage");
        //    }
        //}

        public bool IsMaxImage {
            get
            {
                if (model.WindowState == WindowState.Maximized)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        /// <summary>
        /// 窗口关闭
        /// </summary>
        public void OnClose()
        {
            Application.Current.Shutdown();
        }

        /// <summary>
        /// 窗口最小化
        /// </summary>
        public void OnMin()
        {
            this.model.WindowState = WindowState.Minimized;
        }

        /// <summary>
        /// 修改密码弹窗
        /// </summary>
        public void OnChangePassword()
        {
            //弹出消息框
            ChangePassword box = new ChangePassword();
            var result = box.ShowDialog();
        }

        /// <summary>
        /// 跳转到登录（退出、切换账号）
        /// </summary>
        public void OnLogin()
        {
            Login login = new Login();  //Login为窗口名，把要跳转的新窗口实例化
            login.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            login.Show();  //打开新窗口
            StaticCache.Map.MapHiddenShow();
        }

        /// <summary>
        /// 项目管理
        /// </summary>
        public void OnProject()
        {
            //弹出消息框
            ProjectManagement box = new ProjectManagement();
            var result = box.ShowDialog();
            //todo
        }

        /// <summary>
        /// 权限管理
        /// </summary>
        public void OnAuthority()
        {
            //弹出消息框
            AuthorityManagement box = new AuthorityManagement();
            var result = box.ShowDialog();
        }

        /// <summary>
        /// 最大化
        /// </summary>
        public void OnMax()
        {
            this.model.WindowState = (this.model.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized);
        }

        public void OnSetting()
        {
            AIDistinguishSettings box = new AIDistinguishSettings();
            box.ShowDialog();
        }

        #region Command
        //public RelayCommand Close { get;private set; }

        //public RelayCommand Min { get; private set; }
        //public RelayCommand Menu { get; private set; }
        //public RelayCommand Menu1 { get; private set; }
        //public RelayCommand ChangePassword { get; private set; }
        //public RelayCommand Login { get; private set; }
        //public RelayCommand Project { get; private set; }
        //public RelayCommand Authority { get; private set; }
        //public RelayCommand Max { get; private set; }
        //public RelayCommand Setting { get; private set; }
        #endregion
        #region 数据绑定
        public MainViewData Data { get; private set;  }
        #endregion
    }

    public class JavascriptCallCSharp
    {
        MapViewModel model;
        public JavascriptCallCSharp(MapViewModel model)
        {
            this.model = model;
        }
        public void onToMain(int id)
        {
            //this.model.model.map.ShowDevTools();
            App.Current.Dispatcher.Invoke((Action)(() =>
            {
                MainWindow mainWindow = new MainWindow(id);
                mainWindow.WindowState = WindowState.Maximized;
                mainWindow.Show();  //打开新窗口
                StaticCache.Map.MapHiddenShow();
            }));
        }

        /// <summary>
        /// 窗口关闭
        /// </summary>
        public void onClose()
        {
            App.Current.Dispatcher.Invoke((Action)delegate ()
            {
                this.model.OnClose();
            });
        }

        /// <summary>
        /// 窗口最小化
        /// </summary>
        public void onMin()
        {
            App.Current.Dispatcher.Invoke((Action)delegate ()
            {
                this.model.OnMin();
            });
        }

        /// <summary>
        /// 最大化
        /// </summary>
        public void onMax()
        {
            App.Current.Dispatcher.Invoke((Action)delegate ()
            {
                this.model.OnMax();
            });
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        public void onChangePassword()
        {
            App.Current.Dispatcher.Invoke((Action)delegate ()
            {
                this.model.OnChangePassword();
            });
        }

        /// <summary>
        /// 跳转到登录（退出、切换账号）
        /// </summary>
        public void onLogin()
        {
            App.Current.Dispatcher.Invoke((Action)delegate ()
            {
                StaticCache.Map.MapHiddenShow();
                this.model.OnLogin();
            });
        }

        /// <summary>
        /// 项目管理
        /// </summary>
        public void onProject()
        {
            App.Current.Dispatcher.Invoke((Action)delegate ()
            {
                this.model.OnProject();
            });
        }

        /// <summary>
        /// 权限管理
        /// </summary>
        public void onAuthority()
        {
            App.Current.Dispatcher.Invoke((Action)delegate ()
            {
                this.model.OnAuthority();
            });
        }

        /// <summary>
        /// 设置
        /// </summary>
        public void onSetting() {
            App.Current.Dispatcher.Invoke((Action)delegate ()
            {
                this.model.OnSetting();
            });
        }

        //public string getPoint() {
        //        string line;
        //    // 创建一个 StreamReader 的实例来读取文件 
        //    // using 语句也能关闭 StreamReader
        //    using (StreamReader sr = new StreamReader($"{AppDomain.CurrentDomain.BaseDirectory}/Resources/file/map.json"))
        //    {
        //        line = sr.ReadToEnd();
        //    }
        //    return line;
        //}
    }
}
